package cn.edu.neusoft.mall.Dao.impl;

import cn.edu.neusoft.framework.db.JDBCTemplate;
import cn.edu.neusoft.framework.db.RowMapper;
import cn.edu.neusoft.mall.Dao.UserDao;
import cn.edu.neusoft.mall.entity.User;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLOutput;
import java.util.Date;
import java.util.List;

public class UserDaoImpl implements UserDao {
    RowMapper<User> rowMapper = new RowMapper<User>() {

        @Override
        public User mapRow(ResultSet rs, int rowNum) throws SQLException {
            User user = new User();
            user.setId(rs.getInt("id"));
            user.setUsername(rs.getString("username"));
            user.setPassword(rs.getString("password"));
            user.setUserType(rs.getString("userType"));
            user.setSex(rs.getString("sex"));
            user.setTelephone(rs.getString("telephone"));
            user.setName(rs.getString("name"));
            user.setPasswordSecret(rs.getString("password"));
            return user;
        }
    };


    @Override
    public List<User> getUserList() {
        String sql = "select * from user ";
        return JDBCTemplate.query(sql, rowMapper,null);
    }

    @Override
    public User getUserByNum(String num) {
        String sql = "select * from user where username = ?";
        List<User> userList = JDBCTemplate.query(sql, rowMapper, num);
        if (userList.size() == 0) {
            return null;
        } else {
            return userList.get(0);
        }
    }

    @Override
    public int insertUser(User user) {
        String sql = "INSERT INTO user(username,password,userType,telephone,sex,name) VALUES (?,?,?,?,?,?)";
        return JDBCTemplate.update(sql, user.getUsername(), user.getPasswordSecret(), user.getUserType(), user.getTelephone(), user.getSex(), user.getName());
    }

    @Override
    public int deleteUser(int userId) {
        String sql = "DELETE FROM user WHERE id = ?";
        return JDBCTemplate.update(sql, userId);
    }

    @Override
    public int updateUser(User user, User user1) {
        String sql = "UPDATE user SET username=?, password=?, userType=?, telephone=?, sex=?, name=? WHERE id=?";
        return JDBCTemplate.update(sql, user1.getUsername(), user.getPasswordSecret(), user.getUserType(), user.getTelephone(), user.getSex(), user.getName(), user1.getId());
    }
}